export function imageToDataURL(src) {
  const canvas = document.createElement('CANVAS');
  const ctx = canvas.getContext('2d');
  const img = new Image();
  img.setAttribute('crossOrigin', 'Anonymous');
  img.src = src;
  return new Promise((resolve) => {
    img.onload = function onload() {
      canvas.width = img.width;
      canvas.height = img.height;
      ctx.drawImage(img, 0, 0);
      resolve(canvas.toDataURL('image/jpeg'));
    };
  });
}

export function render(template, data) {
  const ks = Object.keys(data);
  const vs = ks.map((k) => data[k]);

  const t = `return \`${template}\``;
  const f = new Function(...ks, t); // eslint-disable-line

  return f(...vs);
}

export function setTitle(title) {
  document.title = title; // 动态设置用于6个卡片的标题显示
  const mobile = navigator.userAgent.toLowerCase();
  /* 查看机型 */
  if (/iphone|ipad|ipod/.test(mobile)) {
    const iframe = document.createElement('iframe');
    iframe.src = '/favicon.ico';
    iframe.style.display = 'none';
    const iframeCallback = function iframeCallback() {
      setTimeout(() => {
        iframe.removeEventListener('load', iframeCallback);
        document.body.removeChild(iframe);
      }, 0);
    };
    iframe.addEventListener('load', iframeCallback);
    document.body.appendChild(iframe);
  }
}
